<template>
  <div>
    <div id="form1" style="margin-left:30px">
      <el-form
        :inline="true"
        :model="formInline"
        class="demo-form-inline"
        @keyup.enter.native="search()"
        id="shareSearchForm"
      >
        <el-form-item label="大区名称" v-if="isJT">
          <br />
          <br />
          <el-input
            v-model="formInline.theaterName"
            placeholder
            style="margin-left:-80px;width:200px"
          ></el-input>
        </el-form-item>
        <el-form-item label="营销区域名称" v-if="isZQ" style="margin-left:15px">
          <br />
          <br />
          <el-input
            v-model="formInline.baseName"
            placeholder
            style="margin-left:-80px;width:200px"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="门店名称"
          v-if="orgType != '4'"
          style="margin-left:15px"
        >
          <br />
          <br />
          <el-input
            v-model="formInline.shopName"
            placeholder
            style="margin-left:-80px;width:200px"
          ></el-input>
        </el-form-item>
        <el-form-item label="分享日期" style="margin-left:15px">
          <br />
          <br />
          <!--
          <el-date-picker
            v-model="formInline.shareDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
          -->
          <el-date-picker
            v-model="formInline.dateRange"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="margin-left:-80px;width:400px"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item style="margin-left:800px;width:300px">
          <el-button
            type="primary"
            @click="search()"
            size="mini"
            icon="el-icon-search"
            >查询</el-button
          >
          <el-button
            type="primary"
            @click="kong()"
            size="mini"
            icon="el-icon-delete"
            >清空</el-button
          >
          <el-button
            type="success"
            @click="exportExcel()"
            size="mini"
            icon="el-icon-s-data"
            :loading="exportLoading"
            >导出</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="topicTable"
      :data="tableData"
      style="width: 100%; margin-bottom: 20px;"
      :header-cell-style="{ background: '#ebecf0', color: '#606266' }"
      :cell-class-name="tableCellClassName"
      v-loading="loading"
      @sort-change="sortTable"
      :row-key="getRowKey"
      :expand-row-keys="expandRowKeys"
      default-expand-all
      border
      lazy
      :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        v-for="(item, index) in col"
        :key="`col_${index}`"
        :prop="dropCol[index].prop"
        :width="dropCol[index].width"
        :label="item.label"
        align="left"
      >
        <template slot-scope="scope">
          <span v-if="dropCol[index].prop === 'orgName'">
            <span v-if="scope.row.orgType != 4">{{ scope.row.orgName }}</span>
            <span
              v-if="
                scope.row.orgType == 4 &&
                  scope.row.authCode != null &&
                  scope.row.authCode != ''
              "
              >{{ scope.row.orgName }}（{{ scope.row.authCode }}）</span
            >
          </span>
          <span v-if="dropCol[index].prop != 'orgName'">
            {{ scope.row[dropCol[index].prop] }}
          </span>
        </template>
      </el-table-column>

      <!--
      <el-table-column prop="orgName" label="销售区域" align="left" show-overflow-tooltip width="300">
        <template slot-scope="scope">
            <span v-if="scope.row.orgType != 4">{{scope.row.orgName}}</span>
            <span v-if="scope.row.orgType == 4 && scope.row.authCode != null  && scope.row.authCode != ''">{{scope.row.orgName}}（{{scope.row.authCode}}）</span>
        </template>
      </el-table-column>
      <el-table-column prop="warzoneName" label="所属大区" width="200" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="baseName" label="所属营销区域" width="200" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="storeName" label="店铺名称" width="200" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="companyName" label="经销商名称" width="250" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="count" label="分享拉客数" width="150" align="right"></el-table-column>
      <el-table-column prop="rankNum" label="总部排名" width="150" align="right" :formatter="fixRank"></el-table-column>
      <el-table-column prop="theaterRankNum" label="大区排名" width="150" align="right" :formatter="fixRank"></el-table-column>
      <el-table-column prop="shopRankNum" label="门店排名" width="150" align="right" :formatter="fixRank"></el-table-column>
    -->
      <el-table-column label="明细" width="100" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            @click="showEmployeeList(scope.row)"
            >查看详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!--门店业务员拉客列表弹窗-->
    <el-dialog title="门店人员拉客情况" :visible.sync="dialogEmployeeVisible">
      <el-table
        :data="employeeData"
        stripe
        @sort-change="sortTable2"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      >
        <el-table-column
          property="employeeName"
          label="业务员名称"
          sortable="custom"
          width
          align="left"
        ></el-table-column>
        <el-table-column
          property="count"
          label="拉客数"
          sortable="custom"
          align="right"
        ></el-table-column>
        <el-table-column
          property="shopRankNum"
          label="门店排名"
          sortable="custom"
          width
          align="right"
          :formatter="fixRank"
        ></el-table-column>
      </el-table>
      <el-form :inline="true">
        <el-form-item style="margin-top: 16px;"></el-form-item>
      </el-form>
      <div class="block" style="margin-top:-49px">
        <el-pagination
          @size-change="handleSizeChange2"
          @current-change="handleCurrentChange2"
          :page-sizes="[10, 20, 30, 50, 100, 150, 200]"
          :current-page="listQuery2.current"
          :page-size="listQuery2.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total2"
        ></el-pagination>
      </div>
    </el-dialog>

    <!--
    <el-form :inline="true" :model="formInline">
      <el-form-item style="margin-top: 6px;"></el-form-item>
    </el-form>
    -->
    <!--
    <div class="block" style="margin-top:-49px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 50, 100]"
        :current-page="listQuery.current"
        :page-size="listQuery.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    -->
  </div>
</template>

<script>
import Sortable from 'sortablejs';
import {
  queryOrgTotal,
  queryOrgChildList,
  queryAllOrgTree,
  queryOrgEmployeeShareList,
  excelMemberShareByParam,
} from '@/api/shareManage';
import qs from 'qs';
import FileSaver from 'file-saver';
import XLSX from 'xlsx';

export default {
  data() {
    return {
      logininfo: '',
      orgSeq: '',
      orgType: '',
      isInitExpand: false,
      loading: true,
      exportLoading: false,
      formInline: {
        theaterName: '',
        baseName: '',
        shopName: '',
        shareDate: '',
        dateRange: '',
      },
      col: [
        {
          label: '销售区域',
          prop: 'orgName',
        },
        {
          label: '所属大区',
          prop: 'warzoneName',
        },
        {
          label: '所属营销区域',
          prop: 'baseName',
        },
        {
          label: '店铺名称',
          prop: 'storeName',
        },
        {
          label: '经销商名称',
          prop: 'companyName',
        },
        {
          label: '分享拉客数',
          prop: 'count',
        },
        {
          label: '总部排名',
          prop: 'rankNum',
        },
        {
          label: '大区排名',
          prop: 'theaterRankNum',
        },
        {
          label: '门店排名',
          prop: 'shopRankNum',
        },
      ],
      dropCol: [
        {
          label: '销售区域',
          prop: 'orgName',
        },
        {
          label: '所属大区',
          prop: 'warzoneName',
        },
        {
          label: '所属营销区域',
          prop: 'baseName',
        },
        {
          label: '店铺名称',
          prop: 'storeName',
        },
        {
          label: '经销商名称',
          prop: 'companyName',
        },
        {
          label: '分享拉客数',
          prop: 'count',
        },
        {
          label: '总部排名',
          prop: 'rankNum',
        },
        {
          label: '大区排名',
          prop: 'theaterRankNum',
        },
        {
          label: '门店排名',
          prop: 'shopRankNum',
        },
      ],
      expandRowKeys: [],
      tableData: [],
      tableDataExcel: [], //导出数据
      total: 0,
      listQuery: {
        current: 1,
        size: 10,
      },
      sort: '',
      order: '',
      dialogEmployeeVisible: false,
      employeeParam: {
        shopUuid: '',
        shopIds: '',
        sort: '',
        order: '',
        shareDate: '',
        dateRange: '',
      },
      employeeData: [],
      total2: 0,
      listQuery2: {
        current: 1,
        size: 10,
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            },
          },
        ],
      },
    };
  },
  mounted() {
    this.logininfo = localStorage.getItem('logininfo');
    let orgJson = JSON.parse(this.logininfo);
    if (
      orgJson != null &&
      orgJson.orgList != null &&
      orgJson.orgList.length > 0
    ) {
      this.orgSeq = orgJson.orgList[0].orgSeq;
      this.orgType = orgJson.orgList[0].orgType;
    }
    this.rolemanageone();
    document.body.ondrop = function(event) {
      event.preventDefault();
      event.stopPropagation();
    };
    // this.rowDrop()
    this.columnDrop();
  },
  updated() {
    if (!this.isInitExpand) {
      this.expandAll();
    }
  },
  methods: {
    //拖拽列表
    columnDrop() {
      const wrapperTr = document.querySelector('.el-table__header-wrapper tr');
      this.sortable = Sortable.create(wrapperTr, {
        animation: 180,
        delay: 0,
        onEnd: (evt) => {
          const oldItem = this.dropCol[evt.oldIndex];
          this.dropCol.splice(evt.oldIndex, 1);
          this.dropCol.splice(evt.newIndex, 0, oldItem);
        },
      });
    },
    getRowKey(row) {
      return row.orgSeq;
    },
    /*第一层表格*/
    rolemanageone() {
      let dateRange = null;
      if (
        this.formInline.dateRange != null &&
        this.formInline.dateRange.length == 2
      ) {
        dateRange = this.formInline.dateRange.join(',');
      } else {
        this.formInline.dateRange = '';
      }
      let data = {
        orgSeq: this.orgSeq,
        orgType: this.orgType,
        theaterName: this.formInline.theaterName.trim(),
        baseName: this.formInline.baseName.trim(),
        shopName: this.formInline.shopName.trim(),
        shareDate: this.formInline.shareDate,
        dateRange: dateRange,
        sort: this.sort,
        order: this.order,
      };
      queryOrgTotal(data).then((res) => {
        this.loading = false;
        this.tableData = res.records;
      });
    },
    expandAll() {
      const els = document.getElementsByClassName('el-table__expand-icon');
      if (els.length > 0) {
        for (let i = 0; i < els.length; i++) {
          els[i].click();
          break;
        }
        this.isInitExpand = true;
      }
    },
    search() {
      this.isInitExpand = false;
      this.listQuery.current = 1;
      this.rolemanageone();
    },
    //清空
    kong() {
      this.formInline.theaterName = '';
      this.formInline.baseName = '';
      this.formInline.shopName = '';
      this.formInline.shareDate = '';
      this.formInline.dateRange = '';
    },
    //全数据页面导出
    exportExcel1() {
      this.exportLoading = true;
      //获取数据
      let dateRange = null;
      if (
        this.formInline.dateRange != null &&
        this.formInline.dateRange.length == 2
      ) {
        dateRange = this.formInline.dateRange.join(',');
      } else {
        this.formInline.dateRange = '';
      }
      let data = {
        orgSeq: this.orgSeq,
        orgType: this.orgType,
        theaterName: this.formInline.theaterName.trim(),
        baseName: this.formInline.baseName.trim(),
        shopName: this.formInline.shopName.trim(),
        shareDate: this.formInline.shareDate,
        dateRange: dateRange,
        sort: this.sort,
        order: this.order,
      };
      queryAllOrgTree(data).then((res) => {
        this.tableDataExcel = res.records;
        if (res.records == null || res.records.length == 0) {
          this.$message.error('数据为空无法导出!');
          this.exportLoading = false;
          return;
        } else {
          //要导出去的标题
          var arry = [
            [
              '销售区域',
              '所属大区',
              '所属营销区域',
              '店铺名称',
              '经销商名称',
              '分享拉客数',
              '总部排名',
              '大区排名',
              '门店排名',
            ],
          ];
          this.tableDataExcel
            .map((a, i) => {
              var _arry = [];
              var orgName = a.orgName == null ? '' : a.orgName.toString();
              if (a.orgType == '2') {
                orgName = ' ┣ ' + orgName;
              } else if (a.orgType == '3') {
                orgName = '   ┣ ' + orgName;
              } else if (a.orgType == '4') {
                orgName = '      ┣ ' + orgName;
                if (a.authCode != null && a.authCode != '') {
                  orgName += '（' + a.authCode + '）';
                }
              }
              _arry.push(orgName);
              _arry.push(a.warzoneName == null ? '' : a.warzoneName.toString());
              _arry.push(a.baseName == null ? '' : a.baseName.toString());
              _arry.push(a.storeName == null ? '' : a.storeName.toString());
              _arry.push(a.companyName == null ? '' : a.companyName.toString());
              _arry.push(a.count.toString());
              _arry.push(a.rankNum == 0 ? '' : a.rankNum.toString());
              _arry.push(
                a.theaterRankNum == 0 ? '' : a.theaterRankNum.toString()
              );
              _arry.push(a.shopRankNum == 0 ? '' : a.shopRankNum.toString());
              return _arry;
            })
            .forEach((a) => {
              arry.push(a);
            });
          var sheet = XLSX.utils.aoa_to_sheet(arry);
          sheet['!cols'] = [
            {
              wpx: 300, //销售区域
            },
            {
              wpx: 200, //所属大区
            },
            {
              wpx: 200, //所属营销区域
            },
            {
              wpx: 200, //店铺名称
            },
            {
              wpx: 250, //经销商名称
            },
            {
              wpx: 100, //分享拉客数
            },
            {
              wpx: 100, //总部排名
            },
            {
              wpx: 100, //大区排名
            },
            {
              wpx: 100, //门店排名
            },
          ]; //单元格列宽
          this.exportLoading = false;
          this.openDownloadDialog(
            this.sheet2blob(sheet),
            new Date().toLocaleDateString() + '分享客户查询记录表.xlsx'
          );
        }
      });
    },
    //流导出
    exportExcel() {
      this.exportLoading = true;
      //获取数据
      let dateRange = null;
      if (
        this.formInline.dateRange != null &&
        this.formInline.dateRange.length == 2
      ) {
        dateRange = this.formInline.dateRange.join(',');
      } else {
        this.formInline.dateRange = '';
      }
      let data = {
        orgSeq: this.orgSeq,
        orgType: this.orgType,
        theaterName: this.formInline.theaterName.trim(),
        baseName: this.formInline.baseName.trim(),
        shopName: this.formInline.shopName.trim(),
        shareDate: this.formInline.shareDate,
        dateRange: dateRange,
        sort: this.sort,
        order: this.order,
      };
      this.exportLoading = true;
      excelMemberShareByParam(data).then((res) => {
        this.exportLoading = false;
        let blob = new Blob([res], { type: 'application/vnd.ms-excel' });
        const link = document.createElement('a');
        link.style = 'display:none';
        link.href = URL.createObjectURL(blob);
        link.download =
          new Date().toLocaleDateString() + '分享客户查询记录表.xlsx';
        document.body.appendChild(link);
        link.click();
      });
    },
    load(tree, treeNode, resolve) {
      if (this.orgType == null || this.orgType == '') {
        this.orgType = 1;
      }
      let nodeOrgType = parseInt(this.orgType) + parseInt(treeNode.level);
      let dateRange = null;
      if (
        this.formInline.dateRange != null &&
        this.formInline.dateRange.length == 2
      ) {
        dateRange = this.formInline.dateRange.join(',');
      } else {
        this.formInline.dateRange = '';
      }
      let data = {
        orgSeq: treeNode.rowKey,
        orgType: nodeOrgType,
        theaterName: this.formInline.theaterName,
        baseName: this.formInline.baseName,
        shopName: this.formInline.shopName,
        shareDate: this.formInline.shareDate,
        dateRange: dateRange,
        sort: this.sort,
        order: this.order,
      };
      queryOrgChildList(data).then((res) => {
        resolve(res.records);
      });
    },
    sortTable({ column, prop, order }) {
      this.isInitExpand = false;
      this.sort = prop;
      this.order = order;
      this.rolemanageone();
    },
    handleSizeChange(val) {
      this.isInitExpand = false;
      this.listQuery.size = val;
      this.rolemanageone();
    },
    handleCurrentChange(val) {
      this.isInitExpand = false;
      this.listQuery.current = val;
      this.rolemanageone();
    },
    tableCellClassName({ row, column, rowIndex, columnIndex }) {
      if (
        columnIndex === 0 &&
        (row.orgType == 1 || row.orgType == this.orgType)
      ) {
        return 'theaterTitleStyle';
      } else {
        return '';
      }
    },
    /*第二层表格*/
    showEmployeeList(v) {
      this.employeeData = [];
      this.employeeParam.shopIds = v.shopIds;
      this.employeeParam.shareDate = this.formInline.shareDate;
      let dateRange = null;
      if (
        this.formInline.dateRange != null &&
        this.formInline.dateRange.length == 2
      ) {
        dateRange = this.formInline.dateRange.join(',');
      } else {
        this.formInline.dateRange = '';
      }
      this.employeeParam.dateRange = dateRange;
      this.listQuery2.current = 1;
      this.getEmployeeList();
      this.dialogEmployeeVisible = true;
    },
    getEmployeeList() {
      let data = {
        size: this.listQuery2.size,
        current: this.listQuery2.current,
        condition: this.employeeParam,
      };
      queryOrgEmployeeShareList(data).then((res) => {
        this.total2 = res.total;
        this.employeeData = res.records;
      });
    },
    sortTable2({ column, prop, order }) {
      this.employeeParam.sort = prop;
      this.employeeParam.order = order;
      this.listQuery2.current = 1;
      this.getEmployeeList();
    },
    handleSizeChange2(val) {
      this.listQuery2.size = val;
      this.getEmployeeList();
    },
    handleCurrentChange2(val) {
      this.listQuery2.current = val;
      this.getEmployeeList();
    },
    fixRank(row, column, cellValue, index) {
      if (cellValue == 0) {
        return '';
      } else {
        return cellValue;
      }
    },
    //转下载文件
    sheet2blob(sheet, sheetName) {
      sheetName = sheetName || 'sheet1';
      var workbook = {
        SheetNames: [sheetName],
        Sheets: {},
      };
      workbook.Sheets[sheetName] = sheet;
      // 生成excel的配置项
      var wopts = {
        bookType: 'xlsx', // 要生成的文件类型
        bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
        type: 'binary',
      };
      var wbout = XLSX.write(workbook, wopts);
      var blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });
      // 字符串转ArrayBuffer
      function s2ab(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
        return buf;
      }
      return blob;
    },
    //下载文件触发弹窗
    openDownloadDialog(url, saveName) {
      if (typeof url == 'object' && url instanceof Blob) {
        url = URL.createObjectURL(url); // 创建blob地址
      }
      var aLink = document.createElement('a');
      aLink.href = url;
      aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
      var event;
      if (window.MouseEvent) {
        event = new MouseEvent('click');
      } else {
        event = document.createEvent('MouseEvents');
        event.initMouseEvent(
          'click',
          true,
          false,
          window,
          0,
          0,
          0,
          0,
          0,
          false,
          false,
          false,
          false,
          0,
          null
        );
      }
      aLink.dispatchEvent(event);
    },
  },
  //其他
  computed: {
    isJT: function() {
      if (this.orgType == '' || this.orgType == '1') {
        return true;
      } else {
        return false;
      }
    },
    isZQ: function() {
      if (this.orgType == '' || this.orgType == '1' || this.orgType == '2') {
        return true;
      } else {
        return false;
      }
    },
  },
};
</script>
<style scoped>
#shareSearchForm {
  display: inline-block;
  text-align: left;
  width: 900px;
}
.theaterTitleStyle {
  color: #409eff;
  font-weight: bold;
}
</style>
